import { View, Text } from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage, useDidShow } from '@tarojs/taro';
import { Button, Divider, Space } from '@nutui/nutui-react-taro';
import { useEffect, useMemo, useState } from 'react';
import qs from 'qs';
import { BasicLayout } from '@/layouts';
import { useRequest } from '@/hooks';
import { getApiChoiceOutGetPersonId } from '@/api';
import { Media, Section } from '@/components';
import { parseJson, desensitize, Toast } from '@/utils';
import { FourGreatEnum } from '@/interfaces/fourGreat';
import { usePreselectStore } from '@/models';
import { StorageKey } from '@/constants/storage';
import styles from './index.module.scss';

function Detail() {
  const router = useRouter();
  const { addPerson, persons } = usePreselectStore();
  
  // 使用 state 存储参数，以便在 useDidShow 中更新
  const [personId, setPersonId] = useState<number | undefined>(
    router.params?.id ? Number(router.params.id) : undefined
  );
  const [type, setType] = useState<number | undefined>(
    router.params?.type ? Number(router.params.type) : undefined
  );

  // 判断是否已预选
  const isPreselected = useMemo(() => {
    if (!personId) return false;
    return persons.some((person) => person.id === personId);
  }, [personId, persons]);

  // 获取详情数据
  const { data: detailData, loading, run: fetchDetail } = useRequest(
    getApiChoiceOutGetPersonId,
    {
      manual: true,
      formatResult: (res: any) => {
        return res?.data ?? {};
      },
    },
  );

  // 从路由参数获取 ID 和 type
  const getParamsFromRouter = () => {
    const id = router.params?.id ? Number(router.params.id) : undefined;
    const typeValue = router.params?.type ? Number(router.params.type) : undefined;
    return { id, type: typeValue };
  };

  // 从进入选项获取参数（处理分享场景）
  const getParamsFromEnterOptions = () => {
    try {
      const enterOptions = Taro.getEnterOptionsSync();
      const query = enterOptions?.query || {};
      const id = query.id ? Number(query.id) : undefined;
      const typeValue = query.type ? Number(query.type) : undefined;
      return { id, type: typeValue };
    } catch {
      return { id: undefined, type: undefined };
    }
  };

  // 初始化时获取参数
  useEffect(() => {
    const { id, type: typeValue } = getParamsFromRouter();
    if (id) {
      setPersonId(id);
    }
    if (typeValue) {
      setType(typeValue);
    }
  }, []);

  // 页面显示时重新获取参数（处理分享场景）
  useDidShow(() => {
    // 优先从进入选项获取（分享场景）
    const enterParams = getParamsFromEnterOptions();
    if (enterParams.id) {
      setPersonId(enterParams.id);
    }
    if (enterParams.type !== undefined) {
      setType(enterParams.type);
    } else {
      // 如果没有从进入选项获取到，则从路由参数获取
      const routerParams = getParamsFromRouter();
      if (routerParams.id) {
        setPersonId(routerParams.id);
      }
      if (routerParams.type !== undefined) {
        setType(routerParams.type);
      }
    }
  });

  useEffect(() => {
    if (personId) {
      fetchDetail({ personId });
    }
  }, [personId]);

  // 解析bizData获取扩展信息
  const bizData = useMemo(() => {
    if (!detailData?.bizData) return {};
    return parseJson<{ pictureUrl?: string | string[] }>(detailData.bizData, {});
  }, [detailData?.bizData]);

  // 获取作品图片列表
  const workImages = useMemo(() => {
    const pictureUrl = bizData?.pictureUrl;
    if (!pictureUrl) return [];
    
    // 确保是数组格式
    let images: string[] = [];
    if (Array.isArray(pictureUrl)) {
      images = pictureUrl;
    } else if (typeof pictureUrl === 'string') {
      // 如果是字符串，尝试解析为 JSON
      try {
        const parsed = parseJson(pictureUrl);
        images = Array.isArray(parsed) ? parsed : [parsed].filter(Boolean);
      } catch {
        // 如果解析失败，当作单个 URL 处理
        images = [pictureUrl].filter(Boolean);
      }
    }
    
    // 过滤掉空值和无效 URL
    return images.filter((url) => url && typeof url === 'string' && url.trim() !== '');
  }, [bizData?.pictureUrl]);

  // 获取类型名称
  const typeName = useMemo(() => {
    if (!type) return '';
    const typeKey = Object.keys(FourGreatEnum).find(
      (key) => FourGreatEnum[key as keyof typeof FourGreatEnum] === type
    );
    return typeKey || '';
  }, [type]);

  // 脱敏手机号
  const maskedPhone = useMemo(() => {
    if (!detailData?.phone) return '-';
    return desensitize(detailData.phone);
  }, [detailData?.phone]);

  // 分享功能
  useShareAppMessage(() => {
    const sharePath = `/pages/makeup/detail/index?id=${personId}${type ? `&type=${type}` : ''}`;
    return {
      title: detailData?.name || `${typeName}详情`,
      path: sharePath,
      imageUrl: workImages[0] || '',
    };
  });

  // 处理分享按钮点击
  const handleShare = () => {
    // 触发分享菜单
    Taro.showShareMenu({
      withShareTicket: true,
    });
  };

  // 处理预选按钮点击
  const handlePreselect = () => {
    // 检查是否已登录
    const token = Taro.getStorageSync(StorageKey.TOKEN);
    if (!token) {
      // 未登录，弹窗提示
      Toast.confirm({
        title: '提示',
        content: '请先登录后再进行预选',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 保存当前页面路径和参数，用于登录后返回
            const currentPath = router.path;
            const query = router.params;
            const paramsString = qs.stringify(query);
            const returnPath = `${currentPath}${paramsString ? `?${paramsString}` : ''}`;
            Taro.setStorageSync(StorageKey.APP_START_REDIRECT_PATH, returnPath);
            // 跳转到登录页面
            Taro.navigateTo({ url: '/pages/user/login/index' });
          }
        },
      });
      return;
    }

    // 已登录，保存人员信息到store
    addPerson({
      id: detailData?.id || 0,
      name: detailData?.name,
      bigType: detailData?.bigType,
      price: detailData?.price,
      phone: detailData?.phone,
      bizData: detailData?.bizData,
    });
    Toast.success('已加入预选');
  };

  return (
    <BasicLayout
      title={typeName || '详情'}
      back
      fill
      className={styles.page}
      loading={loading}
      footer={{
        children: (
          <View className={styles.footer}>
            <Button
              className={`${styles.footerButton} ${styles.shareButton}`}
              onClick={handleShare}
              fill="outline"
              openType='share'
            >
              分享
            </Button>
            <Button
              className={`${styles.footerButton} ${styles.preselectButton} ${isPreselected ? styles.disabled : ''}`}
              onClick={handlePreselect}
              type="primary"
              disabled={isPreselected}
            >
              {isPreselected ? '已预选' : '预选'}
            </Button>
          </View>
        ),
      }}
    >
      <View className={styles.content}>
        <View className={styles.title}>{detailData?.name || '-'}</View>
        
        {/* 价格和手机号 */}
        <Space className={styles.infoRow}>
          {detailData?.price && (
            <Text className={styles.price}>¥{detailData.price}</Text>
          )}
          {maskedPhone && (
            <Text className={styles.phone}>{maskedPhone}</Text>
          )}
        </Space>

        <Divider />

        {/* 作品展示 */}
        {workImages.length > 0 && (
          <Section title="作品展示" className={styles.section}>
            <View className={styles.workGrid}>
              {workImages.map((image, index) => (
                <View key={index} className={styles.workItem}>
                  <Media
                    src={image}
                    mode="aspectFill"
                    preview
                    className={styles.workMedia}
                    width="100%"
                    height="100%"
                  />
                </View>
              ))}
            </View>
          </Section>
        )}
      </View>
    </BasicLayout>
  );
}

export default Detail;
